<template>
  <div class="app-main-container">
    <div class="df goods_sale_wrap">
      <div class="sell_left">
        <el-input
          v-model="filters.goodsName"
          placeholder="输入商品名称/条形码"
          clearable
          @keyup.enter.native="codeEnter"
        >
          <el-button slot="append" icon="el-icon-search" @click="getList(1)" />
        </el-input>
        <div class="goods_tabs_wrap">
          <div class="list_wrap">
            <img class="btn btn_left" src="@/assets/images/ic_left.png" alt="" @click="moveTabs('left')">
            <img class="btn btn_right" :class="{shadow: tabsBtnShadow}" src="@/assets/images/ic_right.png" alt="" @click="moveTabs('right')">
            <div id="scrollContent" class="list">
              <span class="empty" />
              <span
                v-for="item in typeList"
                :key="item.id"
                :class="{ active: item.name === selectType.name }"
                class="item"
                @click="goodsTabsClick(item)"
              >{{ item.name }}</span>
              <span class="empty" />
            </div>
          </div>
        </div>
        <div class="goods_wrap">
          <div class="good_content">
            <template
              v-for="(item, index) in goodsList"
            >
              <div :key="index" class="card_style" :class="{'selected':item.isSelect}" @click="goodsItemClick(item,index)">
                <img :src="item.picture" class="goods-image" alt="">
                <div class="right-items">
                  <div class="goods-name">
                    {{
                      item.name.length > 8
                        ? item.name.slice(0, 6) + "..."
                        : item.name
                    }}
                  </div>
                  <div class="stock-style">
                    <span class="stock-title-style">库存：</span>
                    <span class="stock-value-style">{{ item.stock }}</span>
                  </div>
                  <div class="add-module-style">
                    <div class="secondColor">￥{{ item.price }}</div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
        <Paginations
          :total="totalCount"
          :page-size="pagination.rows"
          :page="pagination.page"
          :integrated="integrated"
          @current-change="getList"
        />
      </div>
      <div class="sp" />
      <div class="goods_right">
        <div class="member_wrap">
          <div class="df">
            <MemberSearch ref="MemberSearchRef" class="flex1" @clear="memberClear" @select="memberSelect" />
            <el-button class="ml10" type="primary" @click="memberClear">散客</el-button>
          </div>
          <div class="df mt20 mb20">
            <span class="flex1">姓名：{{ memberInfo.nickName || '-' }}</span>
            <span class="flex1">手机号：{{ memberInfo.phone || '-' }}</span>
            <span class="flex1">会员等级：{{ memberInfo.cardName || '-' }}</span>
            <span class="flex1">充值余额：{{ memberInfo.rechargeMoney || '0.00' }}</span>
            <span class="flex1">赠送余额：{{ memberInfo.giveMoney || '0.00' }}</span>
          </div>
        </div>
        <div class="table_wrap" style="width: 100%">
          <el-table
            ref="table"
            :data="saleGoodsList"
            element-loading-text="Loading"
            border
            fit
            height="96%"
            :header-row-class-name="'table-header'"
            class="doumee-element-table margin-t-20"
          >
            <el-table-column align="center" label="商品" min-width="80" prop="name" show-overflow-tooltip />
            <el-table-column
              align="center"
              label="单价"
              prop="price"
              show-overflow-tooltip
              min-width="40"
            />
            <el-table-column align="center" label="数量" width="126">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.buynum"
                  class="w100"
                  :min="1"
                  :max="Number(scope.row.stock)"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="折扣" min-width="40" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ '-' }}
              </template>
            </el-table-column> -->
            <el-table-column align="center" label="商品总价" min-width="60" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ (scope.row.buynum * scope.row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="40" align="center" fixed="right">
              <template slot-scope="scope">
                <div class="flex-cc">
                  <el-button
                    type="text"
                    class="secondColor"
                    @click="delSaleGoods(scope.$index)"
                  >删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="saleGoodsList.length" class="final_wrap">
          <div class="price_wrap">
            <div class="sum-style">
              <span class="sum-title">合计：</span>
              <span class="sum-value secondColor">{{ totalPrice() }}</span>
            </div>
          </div>
          <div class="sub_order">
            <el-input v-model="remark" placeholder="请输入订单备注" />
            <el-button class="ml20" type="primary" @click="settleAccount">订单结算</el-button>
            <el-button @click="clearOrder">清空</el-button>
          </div>
        </div>
      </div>
    </div>
    <orderDialog ref="child" @orderSuccess="payOrderSuccess" />
  </div>
</template>

<script>
import {
  goodsClassifyListVenue,
  goodsListVenue,
  goodsDiscount
} from '@/api'
import orderDialog from '@/components/order'
import MemberSearch from '@/components/MemberSearch'
export default {
  name: 'GoodsSale',
  components: {
    orderDialog,
    MemberSearch
  },
  data() {
    return {
      activeTabs: {},
      tabsBtnShadow: true,
      memberInfo: {},
      remark: '',
      totalDistance: 0,
      transformX: 0,
      limitCount: 0,
      scrollWidth: 0,
      clientWidth: 0,
      meta: [],
      listLoading: true,
      activeType: '-1',
      discountInfo: '',
      selectType: {
        id: '-1'
      },
      integrated: false,
      typeList: [],
      goodsList: [],
      saleGoodsList: [],
      list: [],
      pagination: {
        page: 1,
        rows: 30
      },
      totalCount: 0,
      swiperOptions: {
        slidesPerView: 4,
        slidesPerColumnFill: 'row',
        slidesPerColumn: 4,
        observer: true, // 当改变swiper的样式（例如隐藏/显示）或者修改swiper的子元素时，自动初始化swiper
        observeParents: true, // 修改swiper的父元素时，自动初始化swiper
        pagination: {
          el: '.swiper-pagination-page'
        }
      },
      filters: {
        goodsName: ''
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getClassifyList()
    this.getList(1)
  },
  mounted() {
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    memberClear() {
      this.$refs.MemberSearchRef.clearSearch()
      this.memberInfo = {}
    },
    moveTabs(direction) {
      const scrollContent = document.querySelector('#scrollContent')
      if (this.limitCount === 0) {
        const scrollWidth = scrollContent.scrollWidth // 一共可以滚动的宽度
        const clientWidth = scrollContent.clientWidth // 本身占据的宽度

        this.scrollWidth = scrollWidth
        this.clientWidth = clientWidth
        this.totalDistance = scrollWidth - clientWidth

        this.scrollWidth = scrollWidth
        this.clientWidth = clientWidth
      }
      if (this.totalDistance > 0 && direction === 'right') {
        this.transformX = this.transformX - 450
        scrollContent.style.transform = `translate(${this.transformX}px)`
        this.totalDistance = this.totalDistance - 450
      } else if (this.totalDistance < (this.scrollWidth - this.clientWidth) && direction === 'left') {
        this.transformX = this.transformX + 450
        scrollContent.style.transform = `translate(${this.transformX}px)`
        this.totalDistance = this.totalDistance + 450
      }
      console.log(this.totalDistance)
      this.tabsBtnShadow = this.totalDistance > -40
      this.limitCount += 1
    },
    memberSelect(item) {
      this.memberInfo = item
    },
    clearOrder() {
      this.saleGoodsList = []
      this.goodsList.forEach(item => {
        item.isSelect = false
      })
    },
    payOrderSuccess() {
      this.memberClear()
      this.clearOrder()
      this.$router.push({ name: 'OrderManager' })
    },
    // 场馆端商品分类列表
    getClassifyList() {
      goodsClassifyListVenue({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          saleType: 0
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.typeList = [{ name: '全部', id: '-1' }, ...res.recordList]
          this.selectType = this.typeList[0]
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 场馆端商品列表
    getList(page) {
      const { pagination } = this
      if (page) pagination.page = page
      goodsListVenue({
        pagination,
        param: {
          classifyId: this.selectType.id === '-1' ? '' : this.selectType.id,
          name: this.filters.goodsName,
          status: '1',
          type: 1,
          venueId: sessionStorage.getItem('venueId'),
          saleType: 0
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.goodsList = res.recordList
          this.totalCount = res.totalCount
          this.goodsList.forEach((item) => {
            item['buynum'] = 1
            this.saleGoodsList.forEach(goods => {
              if (goods.id === item.id) {
                item.isSelect = true
              }
            })
          })
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    codeEnter() {
      this.pagination.page = 1
      const { pagination } = this
      goodsListVenue({
        pagination,
        param: {
          classifyId: this.selectType.id === '-1' ? '' : this.selectType.id,
          name: this.filters.goodsName,
          status: '1',
          type: 1,
          venueId: sessionStorage.getItem('venueId'),
          saleType: 0
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.goodsList = res.recordList
          this.totalCount = res.totalCount
          this.goodsList.forEach((item) => {
            item['buynum'] = 1
            this.saleGoodsList.forEach(goods => {
              if (goods.id === item.id) {
                item.isSelect = true
              }
            })
          })
          if (this.goodsList.length === 1) {
            const obj = JSON.parse(JSON.stringify(this.goodsList[0]))
            this.goodsItemClick(obj, 0)
            this.filters.goodsName = ''
          }
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    toShow(scope) {
      // 展示折扣详情
      // list
      goodsDiscount({ param: { id: scope.row.id }}).then((res) => {
        if (res.errorCode !== '000000') return
        const discountInfo = res.recordList
        var memprice = ''
        discountInfo.forEach((item) => {
          memprice = memprice + item.cardName + ':' + item.memberPrice + ' \n '
        })
        this.discountInfo = memprice
      })
    },
    goodsTabsClick(tab, event) {
      this.selectType = tab
      // this.selectType = this.typeList.find((item) => this.activeType === item.id)
      this.getList()
    },
    goodsItemClick(item, index) {
      if (!item.stock || item.stock === '0') {
        return this.$message.info('暂无商品库存')
      }
      if (!item.isSelect) {
        const obj = JSON.parse(JSON.stringify(item))
        this.saleGoodsList.push(obj)
      } else {
        this.saleGoodsList = this.saleGoodsList.filter((goods) => {
          return item.id !== goods.id
        })
      }
      const temp = [...this.goodsList]
      temp[index].isSelect = !temp[index].isSelect
      this.goodsList = temp
    },
    delSaleGoods(index) {
      this.goodsList.forEach(item => {
        if (item.id === this.saleGoodsList[index].id) {
          item.isSelect = false
        }
      })
      this.saleGoodsList.splice(index, 1)
    },
    totalPrice() {
      var totalPrice = 0
      this.saleGoodsList.forEach((goods) => {
        totalPrice += goods.buynum * goods.price
      })
      // for (const goods of this.saleGoodsList) {
      //   totalPrice += goods.buynum * goods.price
      // }
      return totalPrice.toFixed(2)
    },
    settleAccount() {
      // this.dialogTableVisible = true
      const { memberInfo, remark } = this
      const goodsList = []
      this.saleGoodsList.forEach((goods) => {
        goodsList.push({
          id: goods.id,
          goodsNum: goods.buynum
        })
      })
      const config = { goodsList, memberId: memberInfo.id, remark }
      this.$refs.child.continuePay(config, 'goodsSale')
    },
    clear() {
      this.filters.goodsName = ''
      this.getList(1)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.app-main-container {
  height: calc(100% - 40px);
}
.goods_sale_wrap{
  height: 100%;
}
.sp{
  margin: 0 20px;
  width: 1px;
  height: 100%;
  background-color: #DFE2E8;
}
.sell_left{
  width: 560px;
  height: 100%;
  .goods_wrap{
    height: calc(100% - 160px);
    overflow: auto;
    .good_content {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
  }
}
.table_wrap {
  height: calc(100% - 200px);
}
.goods_right{
  flex: 1;
}
.goods_tabs_wrap {
  width: 100%;
  margin: 16px 0 20px;
  position: relative;
  overflow: hidden;
  .list_wrap {
    overflow-x: hidden;
    .list {
      display: flex;
      .empty {
        width: 40px;
        box-sizing: border-box;
        flex-shrink: 0;
      }
      .item {
        flex-shrink: 0;
        height: 35px;
        line-height: 35px;
        padding: 0 16px;
        background-color: #f5f7fc;
        border-radius: 2px;
        margin-right: 10px;
        cursor: pointer;
      }
      .active {
        background-color: $primaryColor;
        color: #fff;
      }
    }
  }

  .btn {
    height: 36px;
    width: 30px;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
    z-index: 300;
    cursor: pointer;
  }
  .btn_left {
    left: 0;
  }
  .btn_right {
    right: 0;
  }
  .shadow{
    box-shadow: -2px -2px 4px 0px rgba(0,0,0,0.08);
  }
}
.final_wrap {
  background: #F7F7F7;
  border-radius: 2px;
  padding: 20px;
  .price_wrap{
    display: flex;
    margin-bottom: 20px;
    .sum-style {
      font-size: 16px;
      margin-right: 75px;
      .sum-title {
        color: #222;
      }
      .sum-value {
        font-size: 17px;
        font-weight: 700;
      }
    }
  }
  .sub_order{
    display: flex;
  }
}

.card_style {
  width: calc(33.33% - 8px);
  height: 80px;
  border-radius: 2px;
  border: 1px solid #DFE2E8;
  box-sizing: border-box;
  display: flex;
  margin-right: 12px;
  margin-bottom: 10px;
  padding: 10px;
  cursor: pointer;
  &:nth-of-type(3n){
    margin-right: 0;
  }
  img {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    padding: 0;
    border-radius: 2px;
  }
  .right-items {
    display: flex;
    flex-flow: column;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    .goods-name {
      color: #222;
      font-size: 14px;
      line-height: 14px;
    }
    .stock-style {
      font-size: 12px;
      line-height: 12px;
      .stock-title-style {
        color: #999;
      }
    }
  }
}
.selected{
  background: #F4F7FC;
  border-radius: 2px;
  border: 1px solid $primaryColor;
}
.bottom-style {
  height: 50px;
  border-left: 1px #dfe2e8 solid;
  border-right: 1px #dfe2e8 solid;
  border-bottom: 1px #dfe2e8 solid;
  .sum-style {
    margin-left: 10px;
    margin-top: 17px;
    height: 15px;
    float: left;
    .sum-title {
      color: #222;
      font-size: 13px;
    }
    .sum-value {
      color: #dd0707;
      font-size: 17px;
      font-weight: 700;
    }
  }
  .btn-style {
    float: right;
    width: 80px;
    height: 30px;
    margin-right: 10px;
    margin-top: 10px;
    background-color: #1943a9;
    color: #fff;
    text-align: center;
    border-radius: 4px;
    line-height: 30px;
    font-size: 13px;
    font-weight: 700;
  }
}
.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.pay-style {
  width: 110px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}

.settle-btn-style {
  margin-left: 20px;
}
.pre {
  white-space: pre;
  .discount-title {
    color: #303133;
    font-size: 16px;
    margin-bottom: 12px;
  }
}
</style>
